package com.may.groupchat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @program: com.may.netty
 * @description:
 * @author: Bobby.Ma
 * @create: 2020-09-12 18:26
 **/
public class GroupChatClient {
    /**
     * logger
     */
    private static final Logger log = LoggerFactory.getLogger(GroupChatClient.class);

    //定义相关属性
    private static final String HOST = "127.0.0.1";//服务器ip
    private static final Integer PORT = 9999;//服务器端口
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    //构造器，完场初始化工作
    public GroupChatClient() throws IOException {
        selector = Selector.open();
        //连接服务器
        socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
        //设置非阻塞
        socketChannel.configureBlocking(false);
        //将 socketChannel 注册到 selector
        socketChannel.register(selector, SelectionKey.OP_READ);
        //得到username
        username = socketChannel.getLocalAddress().toString().substring(1);
        log.info(username + " is ok ...");
    }

    //向服务器发送消息
    public void sendMsg(String msg) {
        msg = username + " 说：" + msg;

        try {
            socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //读取从服务器端回复的消息
    public void readMsg() throws IOException {
        if (selector.select() > 0) {//会阻塞在这里
            //有事件发生的通道
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                if (key.isReadable()) {
                    //得到相关通道
                    SocketChannel channel = (SocketChannel) key.channel();
                    //得到一个 buffer
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    //读取
                    channel.read(buffer);
                    //把读到的缓冲区数据转换成字符串
                    String msg = new String(buffer.array());
                    log.info(msg.trim());
                }
                //当前 key 删除，防止重复处理
                iterator.remove();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        //启动客户端
        GroupChatClient chatClient = new GroupChatClient();
        //启动一个线程
        new Thread(() -> {
            while (true) {
                try {
                    chatClient.readMsg();
                    Thread.currentThread().sleep(3000);
                } catch (IOException | InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        //发送数据给服务器
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            chatClient.sendMsg(msg);
        }
    }
}
